set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_VERSION 1)
cmake_minimum_required(VERSION 3.22)

set(CMAKE_C_COMPILER riscv-none-embed-gcc)
set(CMAKE_CXX_COMPILER riscv-none-embed-g++)
set(CMAKE_ASM_COMPILER riscv-none-embed-gcc)
set(CMAKE_AR riscv-none-embed-ar)
set(CMAKE_OBJCOPY riscv-none-embed-objcopy)
set(CMAKE_OBJDUMP riscv-none-embed-objdump)
set(SIZE riscv-none-embed-size)
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)

add_compile_options(-march=rv32imafcxw -mabi=ilp32f -msmall-data-limit=8 -mno-save-restore -fmessage-length=0)
add_compile_options(-fsigned-char -ffunction-sections -fdata-sections -Wunused -Wuninitialized)
add_compile_options($<$<COMPILE_LANGUAGE:ASM>:-x$<SEMICOLON>assembler-with-cpp>)

add_definitions()

project(BHAL C CXX ASM)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_C_STANDARD 11)

include_directories(User Core Debug Peripheral/inc)
file(GLOB_RECURSE SOURCES "User/*.*" "Debug/*.*" "Peripheral/*.*" "Core/*.*")
file(GLOB USER_CODE )
# set(SOURCES ${SOURCES} "Core/core_riscv.c")

set(LINKER_SCRIPT ${CMAKE_SOURCE_DIR}/Ld/Link.ld)
link_libraries(libm.a)
add_link_options(-march=rv32imafcxw -mabi=ilp32f -msmall-data-limit=8 -mno-save-restore -fmessage-length=0 -fsigned-char)
add_link_options(-ffunction-sections -fdata-sections -Wunused -Wuninitialized -T ${LINKER_SCRIPT})
add_link_options(-nostartfiles -Xlinker --gc-sections -Wl,--print-memory-usage,-Map=${PROJECT_BINARY_DIR}/${PROJECT_NAME}.map --specs=nano.specs -lm -u _printf_float -lprintfloat -o)

set(ASM_S "Startup/startup_ch32v30x_D8C.S")

#设定可执行二进制文件的目录
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/OUT)
set(LIBRARY_OUTPUT_PATH  ${PROJECT_SOURCE_DIR}/OUT/Lib)

link_directories( ${PROJECT_SOURCE_DIR}/OUT/Lib)
# link_libraries(libENC.a)
# add_library(ENC STATIC User/main.c)
add_executable(${PROJECT_NAME}.elf ${USER_CODE} ${SOURCES} ${ASM_S} ${LINKER_SCRIPT})
# 编译静态库
# add_library(库名称 STATIC 代码文件名称) 

# 编译动态库
# add_library(库名称 SHARED 代码文件名称) 

set(HEX_FILE ${PROJECT_SOURCE_DIR}/OUT/${PROJECT_NAME}.hex)
set(BIN_FILE ${PROJECT_SOURCE_DIR}/OUT/${PROJECT_NAME}.bin)

# message(STATUS "Enter cmake ${CMAKE_CURRENT_LIST_DIR}")
# message(WARNING "Enter cmake ${CMAKE_CURRENT_LIST_DIR}")
# message(FATAL_ERROR  "Enter cmake ${CMAKE_CURRENT_LIST_DIR}")

add_custom_command(TARGET ${PROJECT_NAME}.elf POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -Oihex $<TARGET_FILE:${PROJECT_NAME}.elf> ${HEX_FILE}
        COMMAND ${CMAKE_OBJCOPY} -Obinary $<TARGET_FILE:${PROJECT_NAME}.elf> ${BIN_FILE}
        COMMENT "Building ${HEX_FILE}
Building ${BIN_FILE}")
